package com.gzc.just.play.client;

import com.gzc.just.play.Const;
import com.gzc.just.play.client.war3server.War3Server;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 监听本地war3 game的6112端口的UDP广播数据包
 */
class LocalWar3GameBroadcast implements Runnable {
    private static final Logger logger = LogManager.getLogger(LocalWar3GameBroadcast.class);
    private final ConnectionWar3ProxyServer connectionWar3ProxyServer;

    public LocalWar3GameBroadcast(ConnectionWar3ProxyServer connectionWar3ProxyServer) {
        this.connectionWar3ProxyServer = connectionWar3ProxyServer;
    }

    @Override
    public void run() {
        try {
            logger.info("localWar3GameBroadcast udp listen start,localIp={},war3Port={}", Client.WAR3_LOCAL_IP.getHostAddress(), Const.WAR3_PORT);
            try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress(Client.WAR3_LOCAL_IP, Const.WAR3_PORT))) {
                logger.info("localWar3GameBroadcast udp listen start ok,localIp={},war3Port={}", Client.WAR3_LOCAL_IP.getHostAddress(), Const.WAR3_PORT);
                byte[] buffer = new byte[1024];

                while (!Thread.interrupted()) {
                    // 接收数据
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    // 阻塞等待数据
                    socket.receive(packet);
                    // 只处理本地war3 game的udp包
                    if (packet.getAddress().getHostAddress().equals(Client.WAR3_LOCAL_IP.getHostAddress())) {
                        logger.info("localWar3GameBroadcast receive udp packet from ip={},port={},data={}",
                                packet.getAddress().getHostAddress(), packet.getPort(),
                                packet.getData());
                        // 广播转发udp包数据
                        for (War3Server value : Client.connectionMap.values()) {
                            connectionWar3ProxyServer.forwardUdpDataToServer(value.getOtherWar3Ip(), packet.getData(), packet.getLength());
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
